<template>
	<el-dialog
		title="choose signal"
		width="80%"
		top="80px"
		:visible.sync="dialogVisible"
		append-to-body
		@open="dialogOpen"
	>
		<div style="height: 500px;overflow-y: auto">
			<div style="margin-bottom: 20px">
				<el-input prefix-icon="el-icon-search" v-model="name" style="width: 240px" placeholder="please input signal name"></el-input>
			</div>
			<el-checkbox
				:indeterminate="isIndeterminate"
				v-model="checkAll"
				@change="handleCheckAllChange"
			>all check</el-checkbox>
			<div style="margin: 15px 0;"></div>
			<el-checkbox-group
				v-model="checkedSignals"
				@change="handleCheckedSignalsChange"
			>
				<el-checkbox
					v-for="signal in filteredSignals"
					:label="signal.column"
					:key="signal.column"
				>{{signal.name}}</el-checkbox>
			</el-checkbox-group>
		</div>
		<div slot="footer" class="dialog-footer">
			<el-button @click="dialogVisible = false">Cancel</el-button>
			<el-button type="primary" @click="onSignalSave">Save</el-button>
		</div>
	</el-dialog>
</template>

<script>
import { escapeRegexpString } from 'element-ui/src/utils/util'

export default {
	name: 'SignalDialog',
	props: {
		visible: {
			type: Boolean,
			default: false
		},
		checked: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			checkAll: false,
			checkedSignals: [],
			isIndeterminate: false,
			signalVisible: false,
			name: null
		}
	},
	computed: {
		dialogVisible: {
			get() {
				return this.visible;
			},
			set(val) {
				val === false && this.resetData();
				this.$emit("update:visible", val);
			}
		},
		signals() {
			return this.$store.state.signals
		},
		filteredSignals() {
			if (this.name && this.name.length) {
				return this.signals.filter(v => new RegExp(this.name.replace("_","\\_"), 'i').test(v.name))
			} else {
				return this.signals
			}
		}
	},
	methods: {
		dialogOpen() {
			this.checkedSignals = this.checked
			this.handleCheckedSignalsChange(this.checked)
		},
		resetData() {},
		onSignalSave() {
			this.$emit("save", this.checkedSignals)
			this.dialogVisible = false
		},
		handleCheckAllChange(val) {
			this.checkedSignals = val ? this.signals.map(v => v.column) : [];
			this.isIndeterminate = false;
		},
		handleCheckedSignalsChange(value) {
			let checkedCount = value.length;
			this.checkAll = checkedCount === this.signals.length;
			this.isIndeterminate = checkedCount > 0 && checkedCount < this.signals.length;
		}
	}
}
</script>

<style scoped>

</style>
